<?php
namespace App\Services\System;

use Illuminate\Http\Request;
use App\Models\System\User as SysUser;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Testing\Fluent\Concerns\Has;

/**
 * 系统用户服务类
 * @package App\Services
 */
class User
{
    /**
     * 构造函数
     */
    public function __construct()
    {

    }

    /**
     * 获取用户数据
     * @param $id
     * @return mixed
     */
    public function get($id)
    {
        return SysUser::findOrFail($id);
    }
    /**
     * 新建或编辑用户
     * @param $postData
     * @return bool
     */
    public function save($postData)
    {
        DB::beginTransaction();
        try{
            $id = $postData['id'] ?? 0;
            if ($id){
                $user = SysUser::withTrashed()->find($id);
            }else{
                $user = new SysUser;
            }
            $user->name = $postData['name'] ?? '';
            $user->avatar = $postData['avatar'] ?? '';
            $user->email = $postData['email'] ?? '';
            $password = $postData['password'] ?? '';
            if ($password){
                $user->password = Hash::make($password);
                $user->password_level = $postData['password_level'] ?? 0;
            }
            $user->role_ids = $postData['role_ids'] ?? [];
            $user->save();
            //权限中间表数据
            $user->roles()->sync(collect($user->role_ids)->pluck('value'));
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 更改用户状态
     * @param $ids
     * @param $status
     * @return mixed
     */
    public function changeStatus($ids, $status)
    {
        $users = SysUser::withTrashed()->findMany($ids);
        if($status == 1){
            if ($users->isNotEmpty()){
                foreach ($users as $user){
                    $user->restore();
                }
            }
            return true;
        }else{
            if ($users->isNotEmpty()){
                foreach ($users as $user){
                    $user->delete();
                }
            }
            return true;
        }
    }

    /**
     * 获取后台用户配置
     * @param $userId
     * @return array
     */
    public function getAdminUserConf($userId)
    {
        $user = SysUser::query()->find($userId);
        $roles = $user->roles()->with('permissions')->get();
        //角色KEY列表
        $userRoleList = $roles->pluck('name')->unique()->all();
        //$permissionSer = new Permission();
        /*if (in_array('super-admin', $userRoleList)){//超级管理员
            $allPsermission = $permissionSer->getCachePermList();
            $userPermissionList = collect($allPsermission)->pluck('name')->unique()->all();
        }else{
            //用户拥有权限
            $userPermissionList = $roles->pluck('permissions')->collapse()->pluck('name')->unique()->all();
            $allPsermission = $permissionSer->getCachePermList();
            //公共权限
            $publicPermissionList = collect($allPsermission)->filter(function ($value, $key) {
                return $value['is_public'] == 1;
            })->pluck('name')->unique()->all();
            $userPermissionList = array_merge($userPermissionList, $publicPermissionList);
        }*/
        $userPermissionList = $user->getPermissionList();
        return [$userRoleList, $userPermissionList];
    }
    /**
     * 保存用户设置
     * @param $postData
     * @return bool
     * @throws \Exception
     */
    public function baseSetting($postData)
    {
        DB::beginTransaction();
        try{
            $id = $postData['id'] ?? 0;
            $user = SysUser::query()->find($id);
            //个人信息
            isset($postData['name']) && $user->name = $postData['name'];
            isset($postData['avatar']) && $user->avatar = $postData['avatar'];
            isset($postData['profile']) && $user->avatar = $postData['profile'];
            isset($postData['phone']) && $user->avatar = $postData['phone'];
            isset($postData['address']) && $user->avatar = $postData['address'];
            isset($postData['country']) && $user->avatar = $postData['country'];
            isset($postData['geographic']) && $user->geographic = $postData['geographic'];
            isset($postData['geographic_name']) && $user->geographic = $postData['geographic_name'];
            isset($postData['tags']) && $user->tags = (array) $postData['tags'];
            $user->save();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 重置密码
     * @param $postData
     * @return bool
     */
    public function resetPwd($postData){
        $id = $postData['id'] ?? 0;
        $user = SysUser::query()->find($id);
        $old = $postData['old'] ?? '';
        if (!Hash::check($old, $user->password)){
            throw new \Exception('您输入的旧密码不正确');
        }
        //密码
        $password = $postData['password'] ?? '';
        $confirm = $postData['confirm'] ?? '';
        if ($password != $confirm){
            throw new \Exception('两次密码输入不一致，请再次确认');
        }
        if ($password){
            $user->password = Hash::make($password);
            $user->password_level = $postData['password_level'] ?? 0;
        }
        return $user->save();
    }
}
